package com.kf.lib_network.interceptor

import com.blankj.utilcode.util.LogUtils
import com.kf.lib_network.utils.SignUtils
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject

class SignInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val body = request.body()
        val buffer = Buffer()
        body!!.writeTo(buffer)
        val sign = buffer.readUtf8()
        LogUtils.e("SignInterceptor:$sign")
        val jsonObject = JSONObject(sign)
        val stringBuffer = StringBuffer()
        val keys = jsonObject.keys()
        while (keys.hasNext()) {
            stringBuffer.append(jsonObject.get(keys.next()))
        }
        val signMD5 = SignUtils.signMD5(stringBuffer.toString())
        jsonObject.put("sign", signMD5)
        val builder = request.newBuilder()
        val requestBody = RequestBody.create(
            MediaType.parse("application/json;charset=UTF-8"),
            jsonObject.toString()
        )
        builder.post(requestBody)
        return chain.proceed(builder.build())
    }
}